Ext.define('Module.System.MenuManager', {
	extend : 'Ext.panel.Panel',
	alias : 'widget.menumanager',
//	border: false,
	layout: 'fit',
	initComponent : function() {
		var me = this;
		var menutree = me.menutree =  Ext.create('Ext.tree.Panel',{
			title: '菜单管理',
			rootVisible: false,
			border: false,
			width: 450,
			region: 'west',
			tbar: [{
				text: '添加资源',
				iconCls: 'icon-add',
				handler: function(){
					var rec = menutree.getSelectionModel().getSelection()[0];
					if(rec){
						me.addMenu();
					}
					else{
						Ext.Msg.alert('提示', '请选择资源目录。');
					}
				}
			},{
				text: '修改资源',
				iconCls: 'icon-edit',
				handler: function(){
					var rec = menutree.getSelectionModel().getSelection()[0];
					if(rec && rec.data.leaf){
						me.addMenu(rec);
						Ext.getCmp(me.id+'-menuWin').setIconCls('icon-edit');
					}
					else{
						Ext.Msg.alert('提示', '请选择要修改的菜单。');
					}
				}
			},{
				text: '删除资源',
				iconCls: 'icon-delete',
				handler: function(){
					var rec = menutree.getSelectionModel().getSelection()[0];
					if(rec){
						me.delMenu(rec);
					}
					else{
						Ext.Msg.alert('提示', '请选择要删除的菜单。');
					}
				}
			}],
	        viewConfig: {
	            plugins: {
	                ptype: 'treeviewdragdrop'
	            },
                listeners: {
                	beforedrop: function(node,data,overModel,dropPosition,eOpts){
                		var root = menutree.getRootNode();
                		var rec = data.records[0];
                		var _data = data.records[0].data;
                		var node = root.findChild('id',rec.data.id,true);
                		var pnode = node.parentNode;
                		
                		if(node.data.id > 0 && overModel.data.id > 0){
                			
                			return true;
                		}
                		else if(dropPosition == 'append' && overModel.data.id < 0){
                			
                			return true;
                		}
                		
                		return false;
                	},
                	drop: function(node,data,overModel,dropPosition,eOpts ){
                		var root = menutree.getRootNode();
                		var rec = data.records[0];
                		var _data = data.records[0].data;
                		var node = root.findChild('id',rec.data.id,true);
                		var pnode = node.parentNode;
                		rec.set('pid',pnode.data.id);
                		rec.raw.pid = pnode.data.id;
                		var childs = pnode.childNodes;
                		for ( var i = 0; i < childs.length; i++) {
                			var child = childs[i];
                			var params = Ext.apply(child.raw,{index: i});
                			Ext.Ajax.request({
        					    url: 'menu/addMenu.do',
        					    params: params
        					});
						}
                		Ext.getCmp('sys-desk-navigation').store.reload();
                	}
                }
	        },
			store: Ext.create('Ext.data.TreeStore', {
				fields: ['id','index'/*,'leaf'*/,'link','pid','text','linktype','defaultshow'],
		        proxy: {
		            type: 'ajax',
		            url: 'menu/getMenu2.do'
		        },
		        root: {
		            id: '0',
		            text: '根目录(ROOT)',
		            expanded: true,
		            children: me.getMenuFolder()	
		        }
		    }),
		    refresh: function(nodeid,type){
		    	var root = menutree.getRootNode();
		    	root.eachChild(function(node){
		    		if(!node.data.leaf){
		    			node.removeAll();
		    			Ext.Ajax.request({
	        				async: false,
	        				method: 'POST',
	        				params: {node: node.data.id},
	        				url:  'menu/getMenu2.do', 
	        				success: function(response, options) {
	        					var obj = Ext.decode(response.responseText);
	        					Ext.Array.each(obj,function(_data,index){
									var _node = node.appendChild(_data);
									_node.raw = _data;
								});
	        					
	        					Ext.getCmp('sys-desk-navigation').store.reload();
	        				},
	        				failure: function(response, options){
	        					return response;
	        				}
	        			});
		    		}
		    	});
		    	
        		/*var node = root.findChild('id',nodeid,true);
        		node.removeAll();
        		node.expand();
        		if(!node.data.leaf){
        			Ext.Ajax.request({
        				async: true,
        				method: 'POST',
        				params: {node: nodeid},
        				url:  'menu/getMenu2.do', 
        				success: function(response, options) {
        					if(type ||(node.isExpanded() && !type)){
	        					var obj = Ext.decode(response.responseText);
	        					Ext.Array.each(obj,function(_data,index){
									var _node = node.appendChild(_data);
									_node.raw = _data;
								});
        					}
        					Ext.getCmp('sys-desk-navigation').store.reload();
        				},
        				failure: function(response, options){
        					return response;
        				}
        			});
        			
        		}*/
		    },
			columns: [{
				xtype: 'treecolumn', 
	            text: '资源名称',
	            width: 200,
	            sortable: false,
	            dataIndex: 'text'
			},{
				text: '类型',
	            flex: 120,
	            sortable: false,
	            renderer: function(v,met,rec){
	            	switch (rec.raw.leaf) {
					case 0: return '目录';
					case 1: return '资源';
					default: return '目录';
					}
	            }
			}]
		});
		
		
		me.defaults = {padding: 1};
		me.items = [menutree];
		
		
		me.callParent();
	},
	addMenu: function(rec){
		var me = this;
		Ext.create('Ext.window.Window',{
			width: 500,
			height: 310,
			iconCls: 'icon-add',
			id:me.id+'-menuWin',
			modal: true,
			layout: 'fit',
			title: rec ? '编辑资源': "添加资源",
			buttons: [{
				text: '保存',
				handler: function(){
					var formp = this.up('window').down('form');
        	    	var form = formp.form;
        	    	if(form.isValid()){
        	    		form.submit({
            	    	    url: 'menu/addMenu.do',
            	    	    success: function(form, action) {
            	    	    	var rs = Ext.decode(action.response.responseText);
            	    	    	if(rs.rst){
            	    	    		Ext.Msg.alert('提示', rs.msg);
            	    	    		me.menutree.refresh();
            	    	    		formp.up('window').close();
            	    	    		if(rec){
            	    	    			me.menutree.getSelectionModel().clearSelections();
            	    	    		}
            	    	    		/*if(rs.msg != '已存在此类名称的菜单，请重新输入。'){
            	    	    			me.menutree.refresh(form.getValues().pid,rec ? true:false);
            	    	    			formp.up('window').close();
            	    	    		}*/
            	    	    	}
            	    	    	else{
            	    	    		Ext.Msg.alert('提示', '保存失败，请重新尝试。');
            	    	    	}
            	    	    }
            	    	});
        	    	}
        	    	else{
        	    		Ext.Msg.alert('提示', '无效的资源信息,请正确填写资源信息！');
        	    	}
				}
			},{
				text: '取消',
				handler: function(){
					this.up('window').close();
				}
			}],
			items: me.getForm({
				bodyPadding: 20,
				border: false,
				listeners: {
					afterrender: function(fp){
						if(rec){
							fp.form.setValues(rec.raw);
						}
						if(!rec){
							var values = {
								leaf: 1,
								linktype: 0
							};
							var recx = me.menutree.getSelectionModel().getSelection()[0];
							if(recx){
								recx = recx.data.leaf ? recx.parentNode : recx;
							}
							else{
								recx = me.menutree.getRootNode();
							}
							Ext.apply(values,{
								pid: recx.data.id
							});
							fp.form.setValues(values);
						}
					}
				}
			})
		}).show();
	},
	delMenu: function(rec){
		var me = this;
		var id = rec.data.id;
		if(id && '' != id && rec.data.leaf){
			Ext.Msg.confirm('提示', '你确定要删除当前资源吗？',function(b){
				if('yes' == b){
					Ext.Ajax.request({
					    url: 'menu/deleteMenu.do',
					    params: {
					        id: id,
					        menutext:rec.data.text
					    },
					    success: function(response){
					    	var rs = Ext.decode(response.responseText);
	       	    	    	if(rs.rst){
	       	    	    		Ext.Msg.alert('提示', '删除成功！');
	       	    	    		me.menutree.getSelectionModel().deselectAll(true); 
						    	me.menutree.refresh(rec.raw.pid,true);
	       	    	    	}
	       	    	    	else{
	       	    	    		Ext.Msg.alert('提示', '删除失败！详情：<br>'+rs.msg);
	       	    	    	}
					    }
					});
				}
			});
		}
		else{
			Ext.Msg.alert('提示', '请选择要删除的资源！');
		}
	},
	getForm: function(config){
		var me = this;
		var formp = Ext.create('Ext.form.Panel',Ext.apply({
			bodyPadding: 10,
			defaults: {width: 450,xtype: 'fieldset',layout: 'column'},
			items: [{
				title: '基本信息',
				defaults: {columnWidth: 1,allowBlank: false},
				items: [{
					fieldLabel: '资源ID',
					name: 'id',
					xtype: 'hidden'
				},{
					fieldLabel: '资源名称',
					regex: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/,
					regexText : '不能输入特殊字符',
					name: 'text',
					xtype: 'textfield',
					maxLength:20,
					padding: '0 0 5 0'
				},{
					fieldLabel: '上级目录',
					name: 'pid',
					xtype: 'combobox',
					padding: '0 0 5 0',
					xtype: 'combobox',
					store: {
						xtype: 'store',
						fields: ['id', 'text'],
					    data : me.getMenuFolder()
					},
				    queryMode: 'local',
				    displayField: 'text',
				    valueField: 'id'
				},{
					fieldLabel: '序号',
					name: 'index',
					xtype: 'hidden',
					padding: '0 0 5 0'
				},{
					name: 'leaf',
					xtype: 'hidden',
					value: 1
				}]
			},{
				title: '资源设置',
				defaults: {allowBlank: false},
				items: [{
					fieldLabel: '资源类型',
					name: 'linktype',
					columnWidth: 1,
					padding: '0 0 5 0',
					xtype: 'combobox',
					store: {
						xtype: 'store',
						fields: ['v', 'p'],
					    data : [
					        {v: 0,p: '本地资源'},
					        {v: 1,p: '网络资源'}
					    ]
					},
				    queryMode: 'local',
				    displayField: 'p',
				    valueField: 'v'
				},{
					fieldLabel: '资源位置',
					name: 'link',
					columnWidth: 1,
					maxLength:120,
					xtype: 'textfield',
					allowBlank: true
				}]
			}/*,{
				title: '其他信息',
				defaults: {columnWidth: 1,allowBlank: false,value: 0},
				items: [{
					fieldLabel: '默认显示',
					name: 'defaultshow',
					columnWidth: 1,
					padding: '0 0 5 0',
					xtype: 'combobox',
					store: {
						xtype: 'store',
						fields: ['v', 'p'],
					    data : [
					        {v: 0,p: '否'},
					        {v: 1,p: '是'}
					    ]
					},
				    queryMode: 'local',
				    displayField: 'p',
				    valueField: 'v'
				}]
			}*/]
		},config));
		
		return formp;
	},
	getMenuFolder: function(){
		return [{id: -1, text: "系统管理", leaf: false},
                {id: -2, text: "基础信息", leaf: false},
                {id: -3, text: "任务管理", leaf: false},
                {id: -4, text: "视频管理", leaf: false},
                {id: -5, text: "违规管理", leaf: false},
                {id: -6, text: "数据分析", leaf: false}];
	}
});